<template>
  <div class="login-container">
    <!-- 注册背景 -->
    <div class="login-bg" :style="{
        filter: `blur(${bgBlurNum}px)`,
        transform: `scale(${bgScaleNum})`,
      }"></div>
    <!-- 注册窗口 -->
    <div class="login-main">
      <!-- 标题 -->
      <div class="login-title">{{formTitle}}</div>
      <Form ref="loginForm" :model="loginForm" :label-width="70" label-position="left" :rules="loginRules" class="login-form" align-align="left">
        <!-- 用户名 -->
        <FormItem label="用户名" prop="username">
          <Input v-model="loginForm.username" :disabled="formTitle === '个人信息'" placeholder="账号" type="text" size="large" tabindex="1"
            autocomplete>
          </Input>
        </FormItem>
        <!-- 密码 -->
        <FormItem label="密码" prop="password" v-if="formTitle !== '个人信息'">
          <Input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType" placeholder="输入密码"
            size="large" tabindex="2" password>
          </Input>
        </FormItem>
        <!-- 员工姓名 -->
        <FormItem label="姓名" prop="employee_name">
          <Input v-model="loginForm.employee_name" placeholder="员工姓名" size="large" tabindex="1"
            autocomplete>
          </Input>
        </FormItem>
        <!-- 昵称 -->
        <FormItem label="昵称">
          <Input v-model="loginForm.nickname" placeholder="昵称" size="large" tabindex="1"
            autocomplete>
          </Input>
        </FormItem>
        <!-- 邮箱 -->
        <FormItem label="邮箱">
          <Input v-model="loginForm.email" placeholder="邮箱" size="large" tabindex="1"
            autocomplete>
          </Input>
        </FormItem>
        <!-- 部门 -->
        <FormItem label="部门">
          <Select v-model="loginForm.department_id" placeholder="部门" @on-change="handleChangeDepartment" label-in-value>
            <Option v-for="item in department" :value="item.value" :key="Math.random()">{{ item.label }}</Option>
          </Select>
          </Input>
        </FormItem>
        <!-- 职务 -->
        <FormItem label="职务">
          <Select v-model="loginForm.position_id" placeholder="职务" @on-change="handleChangePosition" label-in-value>
            <Option v-for="item in positions" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          </Input>
        </FormItem>
        <!-- 地址 -->
        <FormItem label="地址">
          <Input v-model="loginForm.address" placeholder="地址" size="large" tabindex="1"
            autocomplete>
          </Input>
        </FormItem>
        <!-- 生日 -->
        <FormItem class="birthdate" style="margin-left: 0;">
          <FormItem label="生日" >
            <DatePicker clearable format="yyyy-MM-dd" @on-change="handleBirthDate" v-model="loginForm.date_birth" type="date" placeholder="生日"></DatePicker>
          </FormItem>
          </Input>
        </FormItem>
        <div class="login-operate" v-if="formTitle !== '个人信息'">
          <!-- <Checkbox v-model="isRemberLogin">记住注册</Checkbox> -->
          <Link :underline="false" style="display: block;cursor: pointer;" @click="goLogin" type="primary">去登录</Link>
        </div>
        <!-- 注册 -->
        <Button v-if="formTitle === '个人信息'" :loading="loginLoading" type="primary" tabindex="4" size="large" style="
            width: 100%;
            margin-bottom: 15px;
            font-size: 14px;
            margin-top: 10px;
            border-radius: 6px;
          " @click.native.prevent="handleUpdate">
          {{ loginLoading ? "修改中.." : "确定" }}
        </Button>
        <!-- 注册 -->
        <Button v-else :loading="loginLoading" type="primary" tabindex="4" size="large" style="
            width: 100%;
            margin-bottom: 15px;
            font-size: 14px;
            margin-top: 10px;
            border-radius: 6px;
          " @click.native.prevent="handleLogin">
          {{ loginLoading ? "注册中.." : "注册" }}
        </Button>
      </Form>
    </div>
    <!-- 注册底部 -->
    <div class="login-footer">
      Copyright © 2023 熙薇婚纱摄影.
    </div>
  </div>
</template>

<script>
  import {
    loginBgBlur
  } from "@/settings";
  import { regist, userUpdate } from '@/api/user/index.js'
  export default {
    name: "Login",
    data() {
      return {
        // 注册表单
        loginForm: {
          username: "",
          password: "",
          employee_name: "", // 员工的姓名
          nickname: "", // 昵称
          email: "", // 邮箱
          department_id: "", // 部门id
          department_name: "", // 部门name
          position_id: "", // 职位id
          position_name: "", // 职位name
          address: "", // 地址
          date_birth: "", // 生日
        },
        positions: [],
        // 注册表单验证规则
        loginRules: {
          username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
          password: [{
            required: true,
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请输入密码"));
              } else {
                callback();
              }
            },
          }, ],
          employee_name: [{ required: true, trigger: "blur", message: "请输入员工姓名" }],
        },
        department: [
          {
            value: '1',
            label: '总经办',
            children: [
              { value: '1',label: '财务' },
              { value: '2',label: '客服' },
              { value: '3',label: '人事' },
            ]
          },
          {
            value: '2',
            label: '网络部',
            children: [
              { value: '4',label: '企划/渠道/经理' },
              { value: '5',label: '渠道员/抖音' },
              { value: '5',label: '渠道员/小红书' },
            ]
          },
          {
            value: '3',
            label: '惠阳店',
            children: [
              { value: '6',label: '经理' },
              { value: '7',label: '策划师' },
              { value: '8',label: '邀约师' },
              { value: '9',label: '选片师' },
            ]
          },
          {
            value: '4',
            label: '惠城店',
            children: [
              { value: '6',label: '经理' },
              { value: '7',label: '策划师' },
              { value: '10',label: '礼服师' },
              { value: '9',label: '选片师' },
            ]
          },
          {
            value: '5',
            label: '中山店',
            children: [
              { value: '6',label: '经理' },
              { value: '7',label: '策划师' },
            ]
          },
          {
            value: '6',
            label: '基地',
            children: [
              { value: '11',label: '摄化总监' },
              { value: '12',label: '摄化客服' },
              { value: '13',label: '摄影师' },
              { value: '14',label: '礼服师' },
              { value: '15',label: '化妆师' },
              { value: '16',label: '数码部行政主管' },
              { value: '17',label: '研发数码总监' },
              { value: '18',label: '数码客服' },
              { value: '19',label: '数码师' },
              { value: '20',label: '调色师' },
            ]
          }
        ],
        // 记住注册
        isRemberLogin: false,
        // 验证码图片地址
        validImageUrl: "http://captcha.qq.com/getimage?aid=2000201&uin=0&0.9914836314873827",

        // 注册loading
        loginLoading: false,

        // 切换显示隐藏密码
        passwordType: "password",

        // 跳转注册来源
        redirect: null,
        // 表单title
        formTitle: '用户注册'
      };
    },
    computed: {
      /*
        背景模糊值
        本框架中通过简单放大图片来去除filter的白边。
        也可以通过StackBlur.js来更完美的实现高斯模糊，但是需要多一个依赖包
      */
      bgBlurNum() {
        let num = Number(loginBgBlur);
        if (num < 0) {
          return 0;
        }
        if (num > 100) {
          return 100;
        }
        return num;
      },
      // 背景放大的倍数，主要是配合模糊系数变大有白边的问题
      bgScaleNum() {
        // 模糊值 20-40
        if (this.bgBlurNum >= 20 && this.bgBlurNum < 40) {
          return 1.04;
        }
        // 模糊值 40-60
        else if (this.bgBlurNum >= 40 && this.bgBlurNum < 60) {
          return 1.06;
        }
        // 模糊值 60-80
        else if (this.bgBlurNum >= 60 && this.bgBlurNum < 80) {
          return 1.08;
        }
        // 模糊值 80-100
        else if (this.bgBlurNum >= 80) {
          return 1.1;
        }
        // 模糊值 0-20
        else {
          return 1.02;
        }
      },
    },
    watch: {
      // 监听首页路由地址来源，注册后跳转到该地址
      $route: {
        handler: function(route) {
          this.redirect = route.query && route.query.redirect;
        },
        immediate: true,
      },
      'loginForm.department_id': {
        handler(newValue, oldValue) {
          this.positions = this.department.find(item => item.value === newValue).children
        },
        deep: true,
        immediate: true
      }
    },
    created() {
      if (this.$route.query.state) {
        this.formTitle = this.$route.query.state
      } else {
        this.formTitle = '用户注册'
      }
      console.log(localStorage.getItem('USERINFO'));
      if (localStorage.getItem('USERINFO')) {
        this.loginForm = JSON.parse(localStorage.getItem('USERINFO'))
      }
    },
    mounted() {
      window.addEventListener("keydown", this.onKeyDown);
    },
    destroyed() {
      // 离开页面，清空回车事件
      window.removeEventListener("keydown", this.onKeyDown, false);
    },
    methods: {
      // 修改用户信息
      handleUpdate() {
        this.loginLoading = true;
        const formData = new FormData()
        for (let key in this.loginForm) {
          formData.append(key, this.loginForm[key])
        }
        userUpdate(formData).then(res => {
          console.log('修改用户信息', res);
          this.loginLoading = false;
          if (res.rstpCode == '0000') {
            if (res.data[0]) {
              this.$store.commit("user/SET_NAME", res.data[0].employee_name);
              sessionStorage.setItem("USER_NAME", res.data[0].employee_name);
              localStorage.setItem('USERINFO', JSON.stringify(res.data[0]))
            }
            this.$router.push({ path: "/" });
          } else {
            this.$Message.error(res.rstpMsg);
          }
        })
      },
      // 选择部门
      handleChangeDepartment(option) {
        console.log(option);
        this.loginForm.department_id = option.value;
        this.loginForm.department_name = option.label;
        this.positions = this.department.find(item => item.value === option.value).children
      },
      // 选择职务
      handleChangePosition(option) {
        this.loginForm.position_id = option.value;
        this.loginForm.position_name = option.label;
      },
      // 选择生日
      handleBirthDate(val) {
        console.log(val);
        this.loginForm.date_birth = val
      },
      /**
       * 点击回车注册
       */
      onKeyDown(e) {
        if (e.keyCode == 13) {
          this.handleLogin();
        }
      },
      /**
       * 切换密码显示
       */
      showPwd() {
        if (this.passwordType === "password") {
          this.passwordType = "";
        } else {
          this.passwordType = "password";
        }
        this.$nextTick(() => {
          this.$refs.password.focus();
        });
      },

      /**
       * 点击注册
       */
      handleLogin() {
        this.$refs.loginForm.validate((valid) => {
          if (valid) {
            this.loginLoading = true;
            const formData = new FormData()
            for (let key in this.loginForm) {
              formData.append(key, this.loginForm[key])
            }
            regist(formData).then(res => {
              console.log('注册', res);
              this.loginLoading = false;
              if (res.rstpCode == '0000') {
                this.$router.push({ path: "/login" });
              } else {
                this.$Message.error(res.rstpMsg);
              }
            })
          } else {
            this.loginLoading = false;
            return false;
          }
        });
      },
      /**
       * 点击更改验证码图片
       */
      handleChangeValidImageUrl() {
        this.validImageUrl =
          "http://captcha.qq.com/getimage?aid=2000201&uin=0&0.9914836314873827&t=" +
          new Date().getTime();
      },
      goLogin() {
        this.$router.push({
          path: 'login'
        })
      }
    },
  };
</script>

<style lang="less" scoped>
  .login-container {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 0;
    overflow: hidden;

    // 背景图片，加入高斯模糊
    .login-bg {
      position: absolute;
      background: url("../../assets/login/login_bg_1.jpg") no-repeat;
      background-size: cover;
      background-attachment: fixed;
      background-position: center;
      top: -18px;
      left: -18px;
      right: -18px;
      bottom: -18px;
      z-index: 1;
    }

    // 注册主窗口
    .login-main {
      position: fixed;
      z-index: 10;
      top: 0;
      bottom: auto;
      left: 0;
      right: 0;
      width: 540px;
      min-height: 330px;
      z-index: 1000;
      margin: auto;
      margin-top: 4%;
      border-radius: 6px;
      background: #fff;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

      // 注册标题
      .login-title {
        font-size: 18px;
        font-weight: bold;
        text-align: center;
        color: #303133;
        height: 64px;
        line-height: 64px;
        border-bottom: solid 1px #e8eaec;
      }

      // 注册表单
      .login-form {
        padding: 25px 20px 0px 20px;

        // 定义form表单中svg的样式
        .svg-icon {
          position: absolute;
          top: 0;
          left: 8px;
          bottom: 0;
          color: #808695;
          margin: auto;
        }

        // 验证码样式
        .valid-box {
          display: flex;

          .valid-input {
            flex: 1;
            margin-right: 10px;
          }

          .valid-img {
            width: 140px;
            height: 40px;
            cursor: pointer;
          }
        }
      }

      // 去注册和忘记密码
      .login-operate {
        display: flex;
        justify-content: space-between;

        img {
          width: 24px;
          margin-right: 16px;
          cursor: pointer;
          vertical-align: middle;
          opacity: 0.7;
          transition: all 0.2s ease-in-out;

          &:hover {
            opacity: 1;
          }
        }
      }

      // 注册小提示
      .login-tips {
        font-size: 12px;
        color: #909399;
        padding: 20px;
      }
    }

    // 底部工商备案信息
    .login-footer {
      height: 40px;
      line-height: 40px;
      position: fixed;
      bottom: 0;
      width: 100%;
      text-align: center;
      color: #fff;
      font-family: Arial;
      font-size: 12px;
      letter-spacing: 1px;
      z-index: 10;
    }
  }

  // 是手机设备
  @media screen and (max-width: 640px) {
    .login-container {
      .login-main {
        margin-top: 0;
        width: 100%;
        height: 100%;
        border-radius: 0;
      }
    }
  }
</style>
<style lang="less">
  // view design注册表单样式调整
  .login-form {
    .ivu-input-large {
      font-size: 14px;
    }

    .ivu-form-item-error-tip {
      font-size: 12px;
    }

    .ant-input-prefix {
      color: #808695;
    }
  }
</style>
